package com.weimob.mcloud.wechatwork.customer.mq.artemisUtil.aop;

import com.weimob.artemis.api.enums.RecordStatus;
import com.weimob.artemis.client.consumer.model.ConsumerRecord;
import com.weimob.artemis.client.consumer.model.MessageResult;
import com.weimob.artemis.client.spring.annotation.ArtemisConsumerListener;
import com.weimob.artemis.client.spring.annotation.Subscribe;
import com.weimob.mcloud.wechatwork.customer.externalDependencyProxy.artemisMsg.ArtemisMsgProxy;
import com.weimob.mcloud.wechatwork.customer.mq.artemisUtil.ArtemisExceptionListener;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;

/**
 * 定义消息消费的aop，抓取最后一次Artemis重试异常消息入库
 *
 * @Author LeoLee
 * @Date 2022/8/25 14:56
 * @Version 1.0
 */
@Aspect
@Component
@Slf4j
public class ArtemisExceptionAOP {

    @Autowired
    private ArtemisMsgProxy artemisMsgProxy;

    /**
     * 定义切入点
     */
    @Pointcut("@annotation(com.weimob.mcloud.wechatwork.customer.mq.artemisUtil.ArtemisExceptionListener)")
    public void pointCut() {}

    @Around("pointCut()")
    public void artemisExceptionProcessor(ProceedingJoinPoint joinPoint) throws NoSuchMethodException {

        try {
            Object proceed = joinPoint.proceed();
        } catch (Throwable throwable) {
            //获取切点方法的参数
            Object[] args = joinPoint.getArgs();
            if (args != null && args.length > 0) {
                //只获取第一个参数（Artemis消费者只有一个参数）
                MessageResult messageResult = (MessageResult) args[0];
                //判断是否是最后一次重试，Artemis消费者在消费异常的时候会重复3次
                RecordStatus status = messageResult.getStatus();
                //状态等于1代表是最后一次重试
                if (status.getCode() == 1) {
                    //开始插入数据库
                    Date date = new Date();
                    List<ConsumerRecord> records = messageResult.getRecords();
                    if (CollectionUtils.isNotEmpty(records)) {
                        //获取注解ArtemisConsumerListener的参数
                        Signature signature = joinPoint.getSignature();
                        MethodSignature msg = (MethodSignature) signature;
                        Object target = joinPoint.getTarget();
                        Method method = target.getClass().getMethod(msg.getName(), msg.getParameterTypes());
                        ArtemisConsumerListener artemisConsumerListener = method.getAnnotation(ArtemisConsumerListener.class);
                        ArtemisExceptionListener artemisExceptionListener = method.getAnnotation(ArtemisExceptionListener.class);
                        for (ConsumerRecord consumerRecord : records) {
                            String user = "";
                            for (Subscribe subscribe : artemisConsumerListener.value()) {
                                user = user + subscribe.user();
                            }
                            artemisMsgProxy.insertArtemisExceptionMsg(date, consumerRecord.getTopic(), user, consumerRecord.getKey(), consumerRecord.getValue(), artemisExceptionListener.value(), throwable.getMessage());
                        }
                    } else {
                        log.warn("artemis msg consumerRecord is empty");
                    }
                }
            }
        }


    }
}
